package com.qf.springcloud.zuul.fallback;

import com.sun.xml.internal.messaging.saaj.util.ByteInputStream;
import org.springframework.cloud.netflix.zuul.filters.route.FallbackProvider;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * 只能处理超时异常
 */
@Component
public class ZuulFallback implements FallbackProvider {


    @Override // 针对哪个服务生效
    public String getRoute() {
        return "*";
    }

    @Override
    public ClientHttpResponse fallbackResponse(String route, Throwable cause) {
        // route: 哪个服务除了问题
        // cause: 异常信息
        return new ClientHttpResponse(){

            @Override
            public HttpHeaders getHeaders() {
                HttpHeaders httpHeaders = new HttpHeaders();
                httpHeaders.setContentType(MediaType.TEXT_HTML);
                return httpHeaders;
            }

            @Override
            public InputStream getBody() throws IOException {
                String msg = route + " timeout!!!";
                ByteArrayInputStream byteInputStream = new ByteArrayInputStream(msg.getBytes());
                return byteInputStream;
            }

            @Override
            public HttpStatus getStatusCode() throws IOException {
                return HttpStatus.INTERNAL_SERVER_ERROR;
            }

            @Override
            public int getRawStatusCode() throws IOException {
                return 500;
            }

            @Override
            public String getStatusText() throws IOException {
                return route + " timeout!!!";
            }

            @Override
            public void close() {

            }
        };
    }
}
